﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Security;
using WeProjects.Models;
using WeProjectsModel;

namespace WeProjects.Helps
{
    public static class DataViewModelHelper//:Controller
    {
        private static ProjectsDBEntities db;
        static DataViewModelHelper()
        {
            if(db==null)
            {
                db = new ProjectsDBEntities();
            }
        }
        public static NewsModel ToNewsViewModel(this News news)
        {
            NewsModel vmodel = new NewsModel(news.ID) { isPublic=news.isPublic, isPublished=news.isPublish, MemberID=news.AuthorID, 
                NewsContent=news.NewsContent, ProjectID=news.ProjectID , Title=news.Title, PublishDate=news.PublishDate};            
            var project=db.Projects.Find(news.ProjectID);
            vmodel.ProjectTitle = project.Title;
            if (project.ParentID == null)
            {
                vmodel.ParentProjectTitle = "";
            }
            else
            {
                vmodel.ParentProjectTitle = project.ParentProject.Title;
            }

            var author = db.Members.Find(news.AuthorID);
            if(author!=null)
            {
                vmodel.MemberDispalyName = author.DisplayName;
            }
            var path=Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/NewsPhotos"), news.ID.ToString(), news.ID.ToString() + ".jpg");
            if (File.Exists(path))
            {
                vmodel.ImageData = Utility.GetImage64String(path);
            }  
          
            return vmodel;
        }
        public static NewsModel ToNewsViewModel(this News news, bool requireTags)
        {
            NewsModel vmodel = news.ToNewsViewModel();
            var newsTags=news.Tags.Select(t1 => t1.Code).ToList();
            var tagvModels = db.Tags.Select(t => new TagVModel() { Code = t.Code, Name = t.Name, Selected =newsTags.Contains(t.Code) }).ToList();//news.Tags.Select(t1=>t1.Code).Contains(t.Code)});
            vmodel.Tags = tagvModels.ToList();
            return vmodel;
        }
        public static Project ToProjectDataModel(this ProjectViewModel model)
        {
            Project project = new Project() { ID=model.ID, CreationDate=DateTime.Now, Description=model.Descritpion, OwnerID=model.OwnerID, ParentID=model.ParentID,
             SerialNumber=model.SerialNumber, SubProjectsFileUploadAllowed=model.SubProjectsFileUploadAllowed, TaskDueTimeEnforcement=model.TaskDueTimeEnforcement,Title=model.Title};
            if(model.ParentID==0)
            {
                project.ParentID = null;
            }
            if(model.OwnerID==0)
            {
                project.OwnerID = null;
            }
            return project;
        }
        public static ProjectViewModel ToProjectViewMode(this Project project)
        {
            ProjectViewModel model = new ProjectViewModel() { ID=project.ID, ParentID=project.ParentID, OwnerID=project.OwnerID, 
                CreationDate=project.CreationDate, Title=project.Title, Descritpion=project.Description, SerialNumber=project.SerialNumber,
                SubProjectsFileUploadAllowed=project.SubProjectsFileUploadAllowed, TaskDueTimeEnforcement=project.TaskDueTimeEnforcement,
                OwnerName = project.Owner != null ? project.Owner.Name : "",OwnerDisplayName = project.Owner != null ? project.Owner.DisplayName : ""
            };
            model.Tasks = from t in db.Tasks
                          where t.ProjectID == project.ID
                          select t;
            if(project.ParentProject!=null)
            {
                model.Tasks=model.Tasks.Union<Task>(project.ParentProject.Tasks);
            }
            model.Tasks.OrderBy(t => t.Due);
            model.TaskCount = project.Tasks != null ? project.Tasks.Count() : 0;
            model.NewsCount = project.News.Count;
            model.MemberCount = project.Members.Count;
            model.DocumentCount = project.Documents.Count;

            return model;
        }
        public static MemberViewModel ToMemberViewModel(this Member member)
        {
            MemberViewModel model = new MemberViewModel() { ID=member.ID, DisplayName=member.DisplayName, Email=member.Email, Name=member.Name, Phone=member.Phone };
            model.RoleList = (from r in Roles.GetRolesForUser(member.Name) 
                              select new RoleSelectionModel() { RoleName = r, IsSelected = true, TranslatedRoleName = Utility.Translate<WeProjectsResources.Roles>(r) }).ToList();
            List<RoleSelectionModel> availableRoles=(from r in Roles.GetAllRoles()
                                                     where !Roles.GetRolesForUser(member.Name).Any(r1 => r == r1)
                               select new RoleSelectionModel() { RoleName = r, IsSelected = false, TranslatedRoleName = Utility.Translate<WeProjectsResources.Roles>(r) }).ToList();
            model.RoleList=model.RoleList.Union(availableRoles).ToList();
            return model;
        }
        public static MemberViewModel ToMemberViewModel(this Member member, bool requireAssociatedObjects)
        {
            MemberViewModel model = member.ToMemberViewModel();
            if(requireAssociatedObjects==false)
            {
                return model;
            }
            model.AuthoredNews = (from n in db.News
                                 where n.Author.ID == model.ID
                                 select n).ToList().Select(n1=>n1.ToNewsViewModel());//.ToNullableList();
            model.UploadedDocuments = (from d in db.Documents
                                      where d.UploaderID == model.ID
                                      select d).ToList();
            model.OwnedProjects = (from p in db.Projects
                                  where p.OwnerID == model.ID
                                  select p).ToList().Select(p => p.ToProjectViewMode());//.ToNullableList();
            model.JoinedProjects = member.ProjectsMemberof.ToList().Select(p => p.ToProjectViewMode());//.ToNullableList<ProjectViewModel>();
            return model;
        }
        public static List<T> ToNullableList<T>(this IQueryable<T> query)
        {
            if(query!=null)
            {
                return query.ToList();
            }
            else
            {
                return null;
            }
        }
        //public static List<Member> ToExpertJudgeViewModelList(this IList<Member> users, int activityID = -1)
        //{
        //    var expertModels = new List<MemberViewModel>();
        //    foreach (var e in users)
        //    {
        //        var model = e.to();
        //        foreach (var group in e.ExpertGroups)
        //        {
        //            if (activityID != -1 && group.ActivityID == activityID)
        //            {
        //                model.ExpertGroupCallsign += group.Callsign + " ";
        //            }
        //        }
        //        expertModels.Add(model);
        //    }
        //    return expertModels;
        //}
    }
}